# -*- coding: utf-8 -*-
"""
Created on Fri Sep  9 14:07:24 2022

@author: wulong
"""
'tag = 1 indicates this is first time of iteration'
'data comes from last time step'
'tag != 1 indicates this is not first time of iteration'
'data comes from last iterative step'

import numpy as np
from casadi import *
from Fast_3_formulate_Opt import *
from Obtain_results import *
from Transfer_fast import *

def F3_EMPC(initial_state, state_guess, state_bnds_lo, state_bnds_up,
            slow_state_bnds, fast_1_state_bnds, fast_2_state_bnds,
            slow_input_bnds, fast_1_input_bnds, fast_2_input_bnds,
            input_guess, input_bnds_lo, input_bnds_up,
            input_bin_bnds,
            distb_bnds,
            output_guess, output_bnds_lo, output_bnds_up,
            fast_state_setpnts, fast_input_setpnts,
            alpha, alpha_xf, alpha_uf, pred_horzn,
            pf, pmg, pse,
            tag, pred_horzn_fast_1, pred_horzn_fast_2, X_int_f1, X_int_f2, 
            i, del_Uc, past_Uc, past_Uz,
            alpha_ue, Uc_nb, It_d_Uc, Uc_it_sq,
            pre_d_Uc, pre_sq_Uc, pre_sq_Uz,
            pcm, ppn, rxi, rxi_as, yeb):
    
    f1_x_u = fast_x_u(pred_horzn, pred_horzn_fast_1,
                      fast_1_state_bnds, fast_1_input_bnds, tag, i)
    fast_1_state_bnds_new = f1_x_u[0]
    fast_1_input_bnds_new = f1_x_u[1]
    
    f2_x_u = fast_x_u(pred_horzn, pred_horzn_fast_2,
                      fast_2_state_bnds, fast_2_input_bnds, tag, i)
    fast_2_state_bnds_new = f2_x_u[0]
    fast_2_input_bnds_new = f2_x_u[1]
    
    f_opt = formulate_opt_f3(initial_state, state_guess, state_bnds_lo, state_bnds_up,
                             slow_state_bnds, fast_1_state_bnds_new, fast_2_state_bnds_new,
                             slow_input_bnds, fast_1_input_bnds_new, fast_2_input_bnds_new,
                             input_guess, input_bnds_lo, input_bnds_up,
                             input_bin_bnds,
                             distb_bnds,
                             output_guess, output_bnds_lo, output_bnds_up,
                             fast_state_setpnts, fast_input_setpnts,
                             alpha, alpha_xf, alpha_uf, pred_horzn,
                             pf, pmg, pse, X_int_f1, X_int_f2,
                             i, del_Uc, past_Uc, past_Uz,
                             alpha_ue, Uc_nb, It_d_Uc, Uc_it_sq, tag,
                             pre_d_Uc, pre_sq_Uc, pre_sq_Uz,
                             pcm, ppn, rxi, rxi_as, yeb)
    
    s_opt = solve_opt_f3(*f_opt)
    
    r_opt = get_results_f3(s_opt[0], pred_horzn)
    
    J = s_opt[1]
    
    return r_opt, J
